from DrissionPage import ChromiumPage, SessionPage
from time import sleep
from typing import Callable
import sys, os
from util import file_helper_V_file
from pojo.File import File
from util import my_tkinter


def hqxbqy_获取新标签页(page: ChromiumPage, title: str, time: int):
    wait_time = 0.1
    time = time / wait_time
    for i in range(1, int(time)):
        tab = page.get_tab(title=title)
        if tab != None:
            return tab
        sleep(wait_time)
    return None


def get_tabs_titles_获取所有标签的标题(page: ChromiumPage):
    lis_tabs = page.get_tabs()
    lis_titles = []
    for tab in lis_tabs:
        title = tab.title
        lis_titles.append(title)
    return lis_titles


def hqxbqy_网页操作_获取新标签页(page: ChromiumPage, fun, title: str, time: int):
    wait_time = 0.1
    time = time / wait_time
    lis_titles = get_tabs_titles_获取所有标签的标题(page)
    if fun is not None:
        while True:
            try:
                fun(page)
                break
            except Exception:
                print("dp_helpe38  捕捉到错误，重新尝试")
    for i in range(1, int(time)):
        lis_titles_new = get_tabs_titles_获取所有标签的标题(page)
        if len(lis_titles) != len(lis_titles_new):
            if title in lis_titles_new:
                tab = page.get_tab(title=title)
                return tab
        sleep(wait_time)
        # else:
        # return None
    return None


class xz_下载_class:
    def __init__(self) -> None:
        self.page = SessionPage()

    # def xzwj_下载文件(self, url: str, folder_path: str, file_qz):
    def xzwj_下载文件(self, url: str, file: File):
        file_helper_V_file.gjwjmqzscwj_根据文件名前缀删除文件(file=file)

        # self.page = SessionPage()
        # 保存原始标准输出
        original_stdout = sys.stdout
        # 创建一个空的文件对象
        sys.stdout = open(os.devnull, "w")
        self.page.download(
            url, goal_path=file.folder_path, rename=file.get_qz_获取文件名前缀()
        )
        # 恢复标准输出
        sys.stdout.close()
        sys.stdout = original_stdout

    def close(self):
        self.page.close()


def tzym_跳转页面(url: str, page: ChromiumPage, str_xpath):
    i = 0
    if type(str_xpath) == str:
        str_xpath = [str_xpath]
    while True:
        page.get(url)
        page.wait.doc_loaded()
        for xpath in str_xpath:
            e = page.ele(xpath, timeout=0)
            if e:
                page.wait.doc_loaded()
                return
        i += 1
        if 1 >= 6:
            my_tkinter.文本框("可能出现验证码")
            i = 0
        # if not e:
        #     i += 1
        #     if i == 10:
        #         my_tkinter.文本框("可能出现验证码")
        #         i = 0
        #         sleep(1)
